"""
报告结构生成器

提供学术标准报告模板、结构自动适配算法和内容组织逻辑功能
"""

import logging
import json
import re
from typing import Dict, List, Optional, Any, Tuple, Union, Callable
from dataclasses import dataclass, field
from enum import Enum
import datetime
from pathlib import Path

from ..models.base_models import BaseModel
from .base_component import BaseComponent

logger = logging.getLogger(__name__)


class ReportType(Enum):
    """报告类型"""
    RESEARCH_PAPER = "research_paper"           # 研究论文
    THESIS = "thesis"                          # 学位论文
    CONFERENCE_PAPER = "conference_paper"       # 会议论文
    JOURNAL_ARTICLE = "journal_article"        # 期刊文章
    TECHNICAL_REPORT = "technical_report"       # 技术报告
    SURVEY_PAPER = "survey_paper"              # 综述论文
    SHORT_PAPER = "short_paper"                # 短论文
    POSTER_ABSTRACT = "poster_abstract"        # 海报摘要
    BOOK_CHAPTER = "book_chapter"              # 书籍章节
    DISSERTATION = "dissertation"              # 博士论文


class SectionType(Enum):
    """章节类型"""
    TITLE = "title"                            # 标题
    ABSTRACT = "abstract"                      # 摘要
    KEYWORDS = "keywords"                      # 关键词
    INTRODUCTION = "introduction"              # 引言
    LITERATURE_REVIEW = "literature_review"   # 文献综述
    METHODOLOGY = "methodology"                # 方法论
    RESULTS = "results"                        # 结果
    DISCUSSION = "discussion"                  # 讨论
    CONCLUSION = "conclusion"                  # 结论
    ACKNOWLEDGMENTS = "acknowledgments"        # 致谢
    REFERENCES = "references"                  # 参考文献
    APPENDIX = "appendix"                      # 附录
    FIGURES = "figures"                        # 图表
    TABLES = "tables"                          # 表格
    RELATED_WORK = "related_work"              # 相关工作
    EVALUATION = "evaluation"                  # 评估
    LIMITATIONS = "limitations"                # 局限性
    FUTURE_WORK = "future_work"               # 未来工作


class ContentPriority(Enum):
    """内容优先级"""
    REQUIRED = "required"                      # 必需
    RECOMMENDED = "recommended"                # 推荐
    OPTIONAL = "optional"                      # 可选
    CONDITIONAL = "conditional"                # 条件性


@dataclass
class SectionTemplate(BaseModel):
    """章节模板"""
    section_type: SectionType = SectionType.INTRODUCTION
    title: str = ""
    description: str = ""
    priority: ContentPriority = ContentPriority.RECOMMENDED
    
    # 结构信息
    order: int = 0
    level: int = 1  # 章节层级 (1=章, 2=节, 3=小节)
    parent_section: Optional[str] = None
    subsections: List[str] = field(default_factory=list)
    
    # 内容指导
    content_guidelines: List[str] = field(default_factory=list)
    typical_length: Tuple[int, int] = (500, 1500)  # 典型字数范围
    key_elements: List[str] = field(default_factory=list)
    
    # 格式要求
    formatting_rules: Dict[str, Any] = field(default_factory=dict)
    citation_style: str = "APA"
    
    # 条件逻辑
    inclusion_conditions: List[str] = field(default_factory=list)
    exclusion_conditions: List[str] = field(default_factory=list)
    
    # 内容模板
    content_template: str = ""
    placeholder_patterns: Dict[str, str] = field(default_factory=dict)


@dataclass
class ReportTemplate(BaseModel):
    """报告模板"""
    template_id: str = ""
    name: str = ""
    report_type: ReportType = ReportType.RESEARCH_PAPER
    description: str = ""
    
    # 模板信息
    version: str = "1.0"
    created_date: datetime.datetime = field(default_factory=datetime.datetime.now)
    last_modified: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    # 结构定义
    sections: List[SectionTemplate] = field(default_factory=list)
    section_order: List[str] = field(default_factory=list)
    
    # 格式规范
    page_limit: Optional[Tuple[int, int]] = None  # 页数限制
    word_limit: Optional[Tuple[int, int]] = None  # 字数限制
    reference_limit: Optional[int] = None         # 参考文献数量限制
    
    # 样式配置
    font_family: str = "Times New Roman"
    font_size: int = 12
    line_spacing: float = 1.5
    margin_size: float = 1.0  # 英寸
    
    # 特殊要求
    special_requirements: List[str] = field(default_factory=list)
    submission_guidelines: Dict[str, Any] = field(default_factory=dict)
    
    def get_section_by_type(self, section_type: SectionType) -> Optional[SectionTemplate]:
        """根据类型获取章节"""
        for section in self.sections:
            if section.section_type == section_type:
                return section
        return None
    
    def add_section(self, section: SectionTemplate):
        """添加章节"""
        self.sections.append(section)
        if section.section_type.value not in self.section_order:
            self.section_order.append(section.section_type.value)
        self.last_modified = datetime.datetime.now()
    
    def remove_section(self, section_type: SectionType) -> bool:
        """移除章节"""
        initial_length = len(self.sections)
        self.sections = [s for s in self.sections if s.section_type != section_type]
        
        if len(self.sections) < initial_length:
            if section_type.value in self.section_order:
                self.section_order.remove(section_type.value)
            self.last_modified = datetime.datetime.now()
            return True
        return False
    
    def reorder_sections(self, new_order: List[str]):
        """重新排序章节"""
        self.section_order = new_order
        self.last_modified = datetime.datetime.now()


@dataclass
class ContentBlock(BaseModel):
    """内容块"""
    block_id: str = ""
    section_type: SectionType = SectionType.INTRODUCTION
    title: str = ""
    content: str = ""
    
    # 内容属性
    word_count: int = 0
    paragraph_count: int = 0
    citation_count: int = 0
    
    # 质量评估
    completeness_score: float = 0.0
    coherence_score: float = 0.0
    relevance_score: float = 0.0
    
    # 元数据
    generated_time: datetime.datetime = field(default_factory=datetime.datetime.now)
    last_modified: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    # 依赖关系
    dependencies: List[str] = field(default_factory=list)
    references: List[str] = field(default_factory=list)
    
    def update_statistics(self):
        """更新内容统计"""
        if self.content:
            self.word_count = len(self.content.split())
            self.paragraph_count = len([p for p in self.content.split('\n\n') if p.strip()])
            self.citation_count = len(re.findall(r'\[[\d,\s-]+\]|\([^)]*\d{4}[^)]*\)', self.content))
        self.last_modified = datetime.datetime.now()


@dataclass
class ReportStructure(BaseModel):
    """报告结构"""
    structure_id: str = ""
    template_id: str = ""
    report_type: ReportType = ReportType.RESEARCH_PAPER
    
    # 结构信息
    sections: List[ContentBlock] = field(default_factory=list)
    section_hierarchy: Dict[str, List[str]] = field(default_factory=dict)
    
    # 内容统计
    total_word_count: int = 0
    total_sections: int = 0
    completion_percentage: float = 0.0
    
    # 质量评估
    structure_coherence: float = 0.0
    content_balance: float = 0.0
    overall_quality: float = 0.0
    
    # 生成信息
    generated_time: datetime.datetime = field(default_factory=datetime.datetime.now)
    last_updated: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    def add_content_block(self, block: ContentBlock):
        """添加内容块"""
        self.sections.append(block)
        self.total_sections = len(self.sections)
        self._update_statistics()
    
    def get_section_by_type(self, section_type: SectionType) -> Optional[ContentBlock]:
        """根据类型获取章节"""
        for section in self.sections:
            if section.section_type == section_type:
                return section
        return None
    
    def _update_statistics(self):
        """更新统计信息"""
        self.total_word_count = sum(section.word_count for section in self.sections)
        
        # 计算完成度
        completed_sections = sum(1 for section in self.sections if section.content.strip())
        self.completion_percentage = completed_sections / max(self.total_sections, 1) * 100
        
        self.last_updated = datetime.datetime.now()


@dataclass
class StructureGenerationConfig(BaseModel):
    """结构生成配置"""
    # 基本配置
    report_type: ReportType = ReportType.RESEARCH_PAPER
    target_length: Optional[int] = None  # 目标字数
    page_limit: Optional[int] = None     # 页数限制
    
    # 内容配置
    include_literature_review: bool = True
    include_methodology: bool = True
    include_evaluation: bool = True
    include_limitations: bool = True
    include_future_work: bool = True
    
    # 自适应配置
    auto_adjust_structure: bool = True
    content_driven_organization: bool = True
    
    # 领域配置
    research_domain: str = ""
    target_audience: str = "academic"  # academic, industry, general
    
    # 质量要求
    min_section_length: int = 200
    max_section_length: int = 2000
    balance_threshold: float = 0.3  # 章节长度平衡阈值
    
    # 引用配置
    citation_style: str = "APA"
    min_references: int = 10
    max_references: int = 100


class ReportStructureGenerator(BaseComponent):
    """报告结构生成器"""
    
    def get_required_configs(self) -> List[str]:
        """获取必需的配置项"""
        return []
    
    def _setup_component(self):
        """设置组件特定的初始化逻辑"""
        self.logger.info("报告结构生成器初始化")
        
        # 加载预定义模板
        self.templates: Dict[str, ReportTemplate] = {}
        self._initialize_default_templates()
        
        # 内容组织规则
        self.organization_rules = {
            'logical_flow': self._ensure_logical_flow,
            'content_balance': self._balance_content_distribution,
            'dependency_resolution': self._resolve_section_dependencies,
            'coherence_optimization': self._optimize_coherence
        }
        
        # 章节生成器
        self.section_generators = {
            SectionType.ABSTRACT: self._generate_abstract_structure,
            SectionType.INTRODUCTION: self._generate_introduction_structure,
            SectionType.LITERATURE_REVIEW: self._generate_literature_review_structure,
            SectionType.METHODOLOGY: self._generate_methodology_structure,
            SectionType.RESULTS: self._generate_results_structure,
            SectionType.DISCUSSION: self._generate_discussion_structure,
            SectionType.CONCLUSION: self._generate_conclusion_structure
        }
        
        self.logger.info("报告结构生成器初始化完成")    

    def generate_report_structure(self, 
                                 config: StructureGenerationConfig,
                                 content_context: Dict[str, Any] = None) -> ReportStructure:
        """
        生成报告结构
        
        Args:
            config: 结构生成配置
            content_context: 内容上下文信息
            
        Returns:
            报告结构
        """
        try:
            # 选择或创建模板
            template = self._select_template(config)
            
            # 根据内容上下文调整模板
            if content_context and config.auto_adjust_structure:
                template = self._adapt_template_to_content(template, content_context, config)
            
            # 生成结构
            structure = ReportStructure(
                structure_id=f"struct_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}",
                template_id=template.template_id,
                report_type=config.report_type
            )
            
            # 生成各个章节的内容块
            for section_template in template.sections:
                if self._should_include_section(section_template, config, content_context):
                    content_block = self._generate_content_block(section_template, config, content_context)
                    structure.add_content_block(content_block)
            
            # 应用组织规则
            structure = self._apply_organization_rules(structure, config)
            
            # 评估结构质量
            self._evaluate_structure_quality(structure)
            
            self.logger.info(f"生成报告结构完成: {structure.total_sections} 个章节")
            return structure
            
        except Exception as e:
            self.logger.error(f"生成报告结构失败: {str(e)}")
            raise
    
    def adapt_structure_to_content(self, 
                                  structure: ReportStructure,
                                  available_content: Dict[str, Any],
                                  config: StructureGenerationConfig) -> ReportStructure:
        """
        根据可用内容调整结构
        
        Args:
            structure: 原始结构
            available_content: 可用内容
            config: 配置
            
        Returns:
            调整后的结构
        """
        try:
            adapted_structure = ReportStructure(**structure.to_dict())
            
            # 分析可用内容
            content_analysis = self._analyze_available_content(available_content)
            
            # 调整章节顺序和内容
            for section in adapted_structure.sections:
                section_type = section.section_type
                
                # 根据可用内容调整章节内容
                if section_type.value in available_content:
                    section_content = available_content[section_type.value]
                    section = self._enhance_section_with_content(section, section_content, config)
                
                # 根据内容分析调整章节属性
                if section_type.value in content_analysis:
                    analysis = content_analysis[section_type.value]
                    section = self._adjust_section_based_on_analysis(section, analysis, config)
            
            # 重新评估结构
            self._evaluate_structure_quality(adapted_structure)
            
            return adapted_structure
            
        except Exception as e:
            self.logger.error(f"结构内容适配失败: {str(e)}")
            return structure
    
    def optimize_section_organization(self, 
                                    structure: ReportStructure,
                                    optimization_criteria: Dict[str, float] = None) -> ReportStructure:
        """
        优化章节组织
        
        Args:
            structure: 报告结构
            optimization_criteria: 优化标准
            
        Returns:
            优化后的结构
        """
        try:
            if optimization_criteria is None:
                optimization_criteria = {
                    'logical_flow': 0.3,
                    'content_balance': 0.25,
                    'coherence': 0.25,
                    'completeness': 0.2
                }
            
            optimized_structure = ReportStructure(**structure.to_dict())
            
            # 应用各种优化规则
            for rule_name, weight in optimization_criteria.items():
                if rule_name in self.organization_rules:
                    rule_function = self.organization_rules[rule_name]
                    optimized_structure = rule_function(optimized_structure, weight)
            
            # 重新评估优化后的结构
            self._evaluate_structure_quality(optimized_structure)
            
            self.logger.info("章节组织优化完成")
            return optimized_structure
            
        except Exception as e:
            self.logger.error(f"章节组织优化失败: {str(e)}")
            return structure
    
    def validate_structure_completeness(self, structure: ReportStructure) -> Dict[str, Any]:
        """
        验证结构完整性
        
        Args:
            structure: 报告结构
            
        Returns:
            验证结果
        """
        validation_result = {
            'is_complete': True,
            'missing_sections': [],
            'incomplete_sections': [],
            'quality_issues': [],
            'recommendations': []
        }
        
        try:
            # 获取对应的模板
            template = self.templates.get(structure.template_id)
            if not template:
                validation_result['quality_issues'].append("无法找到对应的模板")
                validation_result['is_complete'] = False
                return validation_result
            
            # 检查必需章节
            required_sections = [s for s in template.sections if s.priority == ContentPriority.REQUIRED]
            existing_section_types = [s.section_type for s in structure.sections]
            
            for required_section in required_sections:
                if required_section.section_type not in existing_section_types:
                    validation_result['missing_sections'].append(required_section.section_type.value)
                    validation_result['is_complete'] = False
            
            # 检查章节完整性
            for section in structure.sections:
                if not section.content.strip():
                    validation_result['incomplete_sections'].append(section.section_type.value)
                elif section.word_count < 50:  # 内容过少
                    validation_result['quality_issues'].append(f"{section.section_type.value} 内容过少")
            
            # 检查结构平衡性
            if structure.content_balance < 0.7:
                validation_result['quality_issues'].append("章节内容分布不平衡")
                validation_result['recommendations'].append("调整各章节内容长度以提高平衡性")
            
            # 检查逻辑连贯性
            if structure.structure_coherence < 0.6:
                validation_result['quality_issues'].append("章节逻辑连贯性不足")
                validation_result['recommendations'].append("重新组织章节顺序以提高逻辑性")
            
            return validation_result
            
        except Exception as e:
            self.logger.error(f"结构完整性验证失败: {str(e)}")
            validation_result['is_complete'] = False
            validation_result['quality_issues'].append(f"验证过程出错: {str(e)}")
            return validation_result
    
    # 模板管理方法
    def _initialize_default_templates(self):
        """初始化默认模板"""
        # 研究论文模板
        research_paper_template = self._create_research_paper_template()
        self.templates[research_paper_template.template_id] = research_paper_template
        
        # 学位论文模板
        thesis_template = self._create_thesis_template()
        self.templates[thesis_template.template_id] = thesis_template
        
        # 会议论文模板
        conference_paper_template = self._create_conference_paper_template()
        self.templates[conference_paper_template.template_id] = conference_paper_template
        
        # 期刊文章模板
        journal_article_template = self._create_journal_article_template()
        self.templates[journal_article_template.template_id] = journal_article_template
        
        # 技术报告模板
        technical_report_template = self._create_technical_report_template()
        self.templates[technical_report_template.template_id] = technical_report_template
    
    def _create_research_paper_template(self) -> ReportTemplate:
        """创建研究论文模板"""
        template = ReportTemplate(
            template_id="research_paper_standard",
            name="标准研究论文",
            report_type=ReportType.RESEARCH_PAPER,
            description="标准学术研究论文模板",
            word_limit=(3000, 8000),
            page_limit=(6, 15)
        )
        
        # 添加章节
        sections = [
            SectionTemplate(
                section_type=SectionType.TITLE,
                title="标题",
                priority=ContentPriority.REQUIRED,
                order=1,
                level=1,
                content_guidelines=[
                    "简洁明确地概括研究内容",
                    "避免使用缩写和专业术语",
                    "长度控制在15个单词以内"
                ],
                typical_length=(10, 50),
                key_elements=["研究主题", "关键概念", "研究范围"]
            ),
            SectionTemplate(
                section_type=SectionType.ABSTRACT,
                title="摘要",
                priority=ContentPriority.REQUIRED,
                order=2,
                level=1,
                content_guidelines=[
                    "包含研究背景、目的、方法、结果和结论",
                    "独立成篇，不依赖正文内容",
                    "使用过去时态描述已完成的工作"
                ],
                typical_length=(150, 300),
                key_elements=["背景", "目的", "方法", "主要发现", "结论"]
            ),
            SectionTemplate(
                section_type=SectionType.KEYWORDS,
                title="关键词",
                priority=ContentPriority.REQUIRED,
                order=3,
                level=1,
                content_guidelines=[
                    "选择3-8个关键词",
                    "涵盖研究的主要概念和领域",
                    "有助于文献检索和分类"
                ],
                typical_length=(20, 100),
                key_elements=["核心概念", "研究方法", "应用领域"]
            ),
            SectionTemplate(
                section_type=SectionType.INTRODUCTION,
                title="引言",
                priority=ContentPriority.REQUIRED,
                order=4,
                level=1,
                content_guidelines=[
                    "介绍研究背景和动机",
                    "阐述研究问题和假设",
                    "概述研究贡献和论文结构"
                ],
                typical_length=(500, 1000),
                key_elements=["研究背景", "问题陈述", "研究目标", "主要贡献", "论文结构"]
            ),
            SectionTemplate(
                section_type=SectionType.RELATED_WORK,
                title="相关工作",
                priority=ContentPriority.RECOMMENDED,
                order=5,
                level=1,
                content_guidelines=[
                    "综述相关研究领域的重要工作",
                    "分析现有方法的优缺点",
                    "明确本研究的创新点和差异"
                ],
                typical_length=(800, 1500),
                key_elements=["文献综述", "方法比较", "研究空白", "本研究定位"]
            ),
            SectionTemplate(
                section_type=SectionType.METHODOLOGY,
                title="方法",
                priority=ContentPriority.REQUIRED,
                order=6,
                level=1,
                content_guidelines=[
                    "详细描述研究方法和实验设计",
                    "提供足够信息以便他人重现",
                    "解释方法选择的理由"
                ],
                typical_length=(800, 1500),
                key_elements=["研究设计", "数据收集", "分析方法", "实验设置", "评估指标"]
            ),
            SectionTemplate(
                section_type=SectionType.RESULTS,
                title="结果",
                priority=ContentPriority.REQUIRED,
                order=7,
                level=1,
                content_guidelines=[
                    "客观呈现实验结果",
                    "使用图表辅助说明",
                    "避免解释和讨论"
                ],
                typical_length=(600, 1200),
                key_elements=["实验数据", "统计分析", "图表展示", "关键发现"]
            ),
            SectionTemplate(
                section_type=SectionType.DISCUSSION,
                title="讨论",
                priority=ContentPriority.REQUIRED,
                order=8,
                level=1,
                content_guidelines=[
                    "解释结果的含义和重要性",
                    "讨论研究的局限性",
                    "与相关研究进行比较"
                ],
                typical_length=(600, 1200),
                key_elements=["结果解释", "理论意义", "实践价值", "局限性", "未来方向"]
            ),
            SectionTemplate(
                section_type=SectionType.CONCLUSION,
                title="结论",
                priority=ContentPriority.REQUIRED,
                order=9,
                level=1,
                content_guidelines=[
                    "总结主要发现和贡献",
                    "回答研究问题",
                    "提出未来研究方向"
                ],
                typical_length=(300, 600),
                key_elements=["主要发现", "研究贡献", "实际应用", "未来工作"]
            ),
            SectionTemplate(
                section_type=SectionType.REFERENCES,
                title="参考文献",
                priority=ContentPriority.REQUIRED,
                order=10,
                level=1,
                content_guidelines=[
                    "包含所有引用的文献",
                    "遵循统一的引用格式",
                    "确保引用的准确性和完整性"
                ],
                typical_length=(200, 1000),
                key_elements=["引用列表", "格式规范", "完整信息"]
            )
        ]
        
        for section in sections:
            template.add_section(section)
        
        return template
    
    def _create_thesis_template(self) -> ReportTemplate:
        """创建学位论文模板"""
        template = ReportTemplate(
            template_id="thesis_standard",
            name="标准学位论文",
            report_type=ReportType.THESIS,
            description="标准学位论文模板",
            word_limit=(15000, 50000),
            page_limit=(50, 200)
        )
        
        # 学位论文的章节结构更详细
        sections = [
            SectionTemplate(
                section_type=SectionType.TITLE,
                title="封面",
                priority=ContentPriority.REQUIRED,
                order=1,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.ABSTRACT,
                title="摘要",
                priority=ContentPriority.REQUIRED,
                order=2,
                level=1,
                typical_length=(500, 1000)
            ),
            SectionTemplate(
                section_type=SectionType.INTRODUCTION,
                title="第一章 绪论",
                priority=ContentPriority.REQUIRED,
                order=3,
                level=1,
                typical_length=(2000, 4000),
                subsections=["研究背景", "研究意义", "研究内容", "论文结构"]
            ),
            SectionTemplate(
                section_type=SectionType.LITERATURE_REVIEW,
                title="第二章 文献综述",
                priority=ContentPriority.REQUIRED,
                order=4,
                level=1,
                typical_length=(3000, 6000)
            ),
            SectionTemplate(
                section_type=SectionType.METHODOLOGY,
                title="第三章 研究方法",
                priority=ContentPriority.REQUIRED,
                order=5,
                level=1,
                typical_length=(2000, 4000)
            ),
            SectionTemplate(
                section_type=SectionType.RESULTS,
                title="第四章 实验结果与分析",
                priority=ContentPriority.REQUIRED,
                order=6,
                level=1,
                typical_length=(4000, 8000)
            ),
            SectionTemplate(
                section_type=SectionType.DISCUSSION,
                title="第五章 讨论",
                priority=ContentPriority.REQUIRED,
                order=7,
                level=1,
                typical_length=(2000, 4000)
            ),
            SectionTemplate(
                section_type=SectionType.CONCLUSION,
                title="第六章 结论与展望",
                priority=ContentPriority.REQUIRED,
                order=8,
                level=1,
                typical_length=(1000, 2000)
            ),
            SectionTemplate(
                section_type=SectionType.ACKNOWLEDGMENTS,
                title="致谢",
                priority=ContentPriority.RECOMMENDED,
                order=9,
                level=1,
                typical_length=(200, 500)
            ),
            SectionTemplate(
                section_type=SectionType.REFERENCES,
                title="参考文献",
                priority=ContentPriority.REQUIRED,
                order=10,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.APPENDIX,
                title="附录",
                priority=ContentPriority.OPTIONAL,
                order=11,
                level=1
            )
        ]
        
        for section in sections:
            template.add_section(section)
        
        return template
    
    def _create_conference_paper_template(self) -> ReportTemplate:
        """创建会议论文模板"""
        template = ReportTemplate(
            template_id="conference_paper_standard",
            name="标准会议论文",
            report_type=ReportType.CONFERENCE_PAPER,
            description="标准会议论文模板",
            word_limit=(2000, 6000),
            page_limit=(4, 12)
        )
        
        # 会议论文通常更简洁
        sections = [
            SectionTemplate(
                section_type=SectionType.TITLE,
                title="标题",
                priority=ContentPriority.REQUIRED,
                order=1,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.ABSTRACT,
                title="摘要",
                priority=ContentPriority.REQUIRED,
                order=2,
                level=1,
                typical_length=(100, 250)
            ),
            SectionTemplate(
                section_type=SectionType.INTRODUCTION,
                title="引言",
                priority=ContentPriority.REQUIRED,
                order=3,
                level=1,
                typical_length=(300, 600)
            ),
            SectionTemplate(
                section_type=SectionType.RELATED_WORK,
                title="相关工作",
                priority=ContentPriority.RECOMMENDED,
                order=4,
                level=1,
                typical_length=(400, 800)
            ),
            SectionTemplate(
                section_type=SectionType.METHODOLOGY,
                title="方法",
                priority=ContentPriority.REQUIRED,
                order=5,
                level=1,
                typical_length=(600, 1200)
            ),
            SectionTemplate(
                section_type=SectionType.EVALUATION,
                title="实验评估",
                priority=ContentPriority.REQUIRED,
                order=6,
                level=1,
                typical_length=(600, 1200)
            ),
            SectionTemplate(
                section_type=SectionType.CONCLUSION,
                title="结论",
                priority=ContentPriority.REQUIRED,
                order=7,
                level=1,
                typical_length=(200, 400)
            ),
            SectionTemplate(
                section_type=SectionType.REFERENCES,
                title="参考文献",
                priority=ContentPriority.REQUIRED,
                order=8,
                level=1
            )
        ]
        
        for section in sections:
            template.add_section(section)
        
        return template
    
    def _create_journal_article_template(self) -> ReportTemplate:
        """创建期刊文章模板"""
        template = ReportTemplate(
            template_id="journal_article_standard",
            name="标准期刊文章",
            report_type=ReportType.JOURNAL_ARTICLE,
            description="标准期刊文章模板",
            word_limit=(4000, 10000),
            page_limit=(8, 20)
        )
        
        # 期刊文章结构相对标准化
        sections = [
            SectionTemplate(
                section_type=SectionType.TITLE,
                title="标题",
                priority=ContentPriority.REQUIRED,
                order=1,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.ABSTRACT,
                title="摘要",
                priority=ContentPriority.REQUIRED,
                order=2,
                level=1,
                typical_length=(200, 350)
            ),
            SectionTemplate(
                section_type=SectionType.KEYWORDS,
                title="关键词",
                priority=ContentPriority.REQUIRED,
                order=3,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.INTRODUCTION,
                title="引言",
                priority=ContentPriority.REQUIRED,
                order=4,
                level=1,
                typical_length=(600, 1200)
            ),
            SectionTemplate(
                section_type=SectionType.LITERATURE_REVIEW,
                title="文献综述",
                priority=ContentPriority.RECOMMENDED,
                order=5,
                level=1,
                typical_length=(800, 1500)
            ),
            SectionTemplate(
                section_type=SectionType.METHODOLOGY,
                title="研究方法",
                priority=ContentPriority.REQUIRED,
                order=6,
                level=1,
                typical_length=(800, 1500)
            ),
            SectionTemplate(
                section_type=SectionType.RESULTS,
                title="结果",
                priority=ContentPriority.REQUIRED,
                order=7,
                level=1,
                typical_length=(800, 1500)
            ),
            SectionTemplate(
                section_type=SectionType.DISCUSSION,
                title="讨论",
                priority=ContentPriority.REQUIRED,
                order=8,
                level=1,
                typical_length=(600, 1200)
            ),
            SectionTemplate(
                section_type=SectionType.LIMITATIONS,
                title="研究局限性",
                priority=ContentPriority.RECOMMENDED,
                order=9,
                level=1,
                typical_length=(200, 400)
            ),
            SectionTemplate(
                section_type=SectionType.CONCLUSION,
                title="结论",
                priority=ContentPriority.REQUIRED,
                order=10,
                level=1,
                typical_length=(400, 800)
            ),
            SectionTemplate(
                section_type=SectionType.REFERENCES,
                title="参考文献",
                priority=ContentPriority.REQUIRED,
                order=11,
                level=1
            )
        ]
        
        for section in sections:
            template.add_section(section)
        
        return template
    
    def _create_technical_report_template(self) -> ReportTemplate:
        """创建技术报告模板"""
        template = ReportTemplate(
            template_id="technical_report_standard",
            name="标准技术报告",
            report_type=ReportType.TECHNICAL_REPORT,
            description="标准技术报告模板",
            word_limit=(5000, 15000),
            page_limit=(10, 30)
        )
        
        # 技术报告更注重实用性
        sections = [
            SectionTemplate(
                section_type=SectionType.TITLE,
                title="标题页",
                priority=ContentPriority.REQUIRED,
                order=1,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.ABSTRACT,
                title="执行摘要",
                priority=ContentPriority.REQUIRED,
                order=2,
                level=1,
                typical_length=(300, 600)
            ),
            SectionTemplate(
                section_type=SectionType.INTRODUCTION,
                title="引言",
                priority=ContentPriority.REQUIRED,
                order=3,
                level=1,
                typical_length=(500, 1000)
            ),
            SectionTemplate(
                section_type=SectionType.METHODOLOGY,
                title="技术方法",
                priority=ContentPriority.REQUIRED,
                order=4,
                level=1,
                typical_length=(1000, 2000)
            ),
            SectionTemplate(
                section_type=SectionType.RESULTS,
                title="实施结果",
                priority=ContentPriority.REQUIRED,
                order=5,
                level=1,
                typical_length=(1000, 2000)
            ),
            SectionTemplate(
                section_type=SectionType.EVALUATION,
                title="性能评估",
                priority=ContentPriority.RECOMMENDED,
                order=6,
                level=1,
                typical_length=(800, 1500)
            ),
            SectionTemplate(
                section_type=SectionType.DISCUSSION,
                title="分析讨论",
                priority=ContentPriority.RECOMMENDED,
                order=7,
                level=1,
                typical_length=(600, 1200)
            ),
            SectionTemplate(
                section_type=SectionType.CONCLUSION,
                title="结论和建议",
                priority=ContentPriority.REQUIRED,
                order=8,
                level=1,
                typical_length=(400, 800)
            ),
            SectionTemplate(
                section_type=SectionType.REFERENCES,
                title="参考文献",
                priority=ContentPriority.RECOMMENDED,
                order=9,
                level=1
            ),
            SectionTemplate(
                section_type=SectionType.APPENDIX,
                title="附录",
                priority=ContentPriority.OPTIONAL,
                order=10,
                level=1
            )
        ]
        
        for section in sections:
            template.add_section(section)
        
        return template  
  
    # 核心生成方法
    def _select_template(self, config: StructureGenerationConfig) -> ReportTemplate:
        """选择合适的模板"""
        template_mapping = {
            ReportType.RESEARCH_PAPER: "research_paper_standard",
            ReportType.THESIS: "thesis_standard",
            ReportType.CONFERENCE_PAPER: "conference_paper_standard",
            ReportType.JOURNAL_ARTICLE: "journal_article_standard",
            ReportType.TECHNICAL_REPORT: "technical_report_standard"
        }
        
        template_id = template_mapping.get(config.report_type, "research_paper_standard")
        return self.templates.get(template_id, self.templates["research_paper_standard"])
    
    def _adapt_template_to_content(self, 
                                  template: ReportTemplate, 
                                  content_context: Dict[str, Any],
                                  config: StructureGenerationConfig) -> ReportTemplate:
        """根据内容上下文调整模板"""
        adapted_template = ReportTemplate(**template.to_dict())
        
        # 根据内容调整章节
        if 'has_experimental_data' in content_context and content_context['has_experimental_data']:
            # 如果有实验数据，确保包含结果和评估章节
            if not adapted_template.get_section_by_type(SectionType.RESULTS):
                results_section = SectionTemplate(
                    section_type=SectionType.RESULTS,
                    title="实验结果",
                    priority=ContentPriority.REQUIRED,
                    order=7,
                    level=1
                )
                adapted_template.add_section(results_section)
        
        if 'has_survey_data' in content_context and content_context['has_survey_data']:
            # 如果有调研数据，强化文献综述章节
            lit_review = adapted_template.get_section_by_type(SectionType.LITERATURE_REVIEW)
            if lit_review:
                lit_review.priority = ContentPriority.REQUIRED
                lit_review.typical_length = (1000, 2000)
        
        if 'research_domain' in content_context:
            domain = content_context['research_domain']
            # 根据研究领域调整章节重点
            if 'machine learning' in domain.lower() or 'ai' in domain.lower():
                # AI/ML领域通常需要详细的评估章节
                eval_section = adapted_template.get_section_by_type(SectionType.EVALUATION)
                if eval_section:
                    eval_section.priority = ContentPriority.REQUIRED
        
        return adapted_template
    
    def _should_include_section(self, 
                               section_template: SectionTemplate,
                               config: StructureGenerationConfig,
                               content_context: Dict[str, Any] = None) -> bool:
        """判断是否应该包含某个章节"""
        # 必需章节总是包含
        if section_template.priority == ContentPriority.REQUIRED:
            return True
        
        # 根据配置决定可选章节
        section_type = section_template.section_type
        
        if section_type == SectionType.LITERATURE_REVIEW and not config.include_literature_review:
            return False
        
        if section_type == SectionType.METHODOLOGY and not config.include_methodology:
            return False
        
        if section_type == SectionType.EVALUATION and not config.include_evaluation:
            return False
        
        if section_type == SectionType.LIMITATIONS and not config.include_limitations:
            return False
        
        if section_type == SectionType.FUTURE_WORK and not config.include_future_work:
            return False
        
        # 检查包含条件
        if section_template.inclusion_conditions and content_context:
            for condition in section_template.inclusion_conditions:
                if not self._evaluate_condition(condition, content_context):
                    return False
        
        # 检查排除条件
        if section_template.exclusion_conditions and content_context:
            for condition in section_template.exclusion_conditions:
                if self._evaluate_condition(condition, content_context):
                    return False
        
        return True
    
    def _generate_content_block(self, 
                               section_template: SectionTemplate,
                               config: StructureGenerationConfig,
                               content_context: Dict[str, Any] = None) -> ContentBlock:
        """生成内容块"""
        block = ContentBlock(
            block_id=f"block_{section_template.section_type.value}_{datetime.datetime.now().strftime('%H%M%S')}",
            section_type=section_template.section_type,
            title=section_template.title
        )
        
        # 使用章节生成器生成初始内容
        if section_template.section_type in self.section_generators:
            generator = self.section_generators[section_template.section_type]
            block.content = generator(section_template, config, content_context)
        else:
            # 使用模板生成基础内容
            block.content = self._generate_template_content(section_template, content_context)
        
        # 更新统计信息
        block.update_statistics()
        
        return block
    
    def _generate_template_content(self, 
                                  section_template: SectionTemplate,
                                  content_context: Dict[str, Any] = None) -> str:
        """使用模板生成内容"""
        if section_template.content_template:
            content = section_template.content_template
            
            # 替换占位符
            if content_context:
                for placeholder, pattern in section_template.placeholder_patterns.items():
                    if placeholder in content_context:
                        content = content.replace(pattern, str(content_context[placeholder]))
            
            return content
        
        # 生成基础结构内容
        content_parts = []
        
        # 添加章节指导
        if section_template.content_guidelines:
            content_parts.append("<!-- 内容指导 -->")
            for guideline in section_template.content_guidelines:
                content_parts.append(f"<!-- {guideline} -->")
            content_parts.append("")
        
        # 添加关键要素提示
        if section_template.key_elements:
            content_parts.append("<!-- 关键要素 -->")
            for element in section_template.key_elements:
                content_parts.append(f"<!-- 需要包含: {element} -->")
            content_parts.append("")
        
        # 添加基础内容框架
        content_parts.append(f"[{section_template.title}内容待完善]")
        content_parts.append("")
        content_parts.append(f"<!-- 建议长度: {section_template.typical_length[0]}-{section_template.typical_length[1]} 字 -->")
        
        return "\n".join(content_parts)
    
    # 章节生成器
    def _generate_abstract_structure(self, 
                                   section_template: SectionTemplate,
                                   config: StructureGenerationConfig,
                                   content_context: Dict[str, Any] = None) -> str:
        """生成摘要结构"""
        abstract_parts = [
            "<!-- 摘要结构 -->",
            "",
            "<!-- 1. 研究背景 (1-2句) -->",
            "[研究背景和问题陈述]",
            "",
            "<!-- 2. 研究目的 (1句) -->", 
            "[研究目的和假设]",
            "",
            "<!-- 3. 研究方法 (2-3句) -->",
            "[研究方法和数据来源]",
            "",
            "<!-- 4. 主要发现 (2-3句) -->",
            "[关键结果和发现]",
            "",
            "<!-- 5. 结论意义 (1-2句) -->",
            "[研究结论和实际意义]"
        ]
        
        return "\n".join(abstract_parts)
    
    def _generate_introduction_structure(self, 
                                       section_template: SectionTemplate,
                                       config: StructureGenerationConfig,
                                       content_context: Dict[str, Any] = None) -> str:
        """生成引言结构"""
        intro_parts = [
            "<!-- 引言结构 -->",
            "",
            "## 研究背景",
            "[介绍研究领域的背景和重要性]",
            "",
            "## 问题陈述", 
            "[明确研究问题和挑战]",
            "",
            "## 研究动机",
            "[解释为什么这个问题值得研究]",
            "",
            "## 研究目标",
            "[具体的研究目标和预期成果]",
            "",
            "## 主要贡献",
            "[本研究的创新点和贡献]",
            "",
            "## 论文结构",
            "[各章节内容概述]"
        ]
        
        return "\n".join(intro_parts)
    
    def _generate_literature_review_structure(self, 
                                            section_template: SectionTemplate,
                                            config: StructureGenerationConfig,
                                            content_context: Dict[str, Any] = None) -> str:
        """生成文献综述结构"""
        review_parts = [
            "<!-- 文献综述结构 -->",
            "",
            "## 理论基础",
            "[相关理论和概念框架]",
            "",
            "## 研究现状",
            "[当前研究领域的发展状况]",
            "",
            "## 方法比较",
            "[现有方法的比较分析]",
            "",
            "## 研究空白",
            "[识别的研究空白和不足]",
            "",
            "## 本研究定位",
            "[本研究在现有研究中的定位]"
        ]
        
        return "\n".join(review_parts)
    
    def _generate_methodology_structure(self, 
                                      section_template: SectionTemplate,
                                      config: StructureGenerationConfig,
                                      content_context: Dict[str, Any] = None) -> str:
        """生成方法论结构"""
        method_parts = [
            "<!-- 方法论结构 -->",
            "",
            "## 研究设计",
            "[整体研究设计和框架]",
            "",
            "## 数据收集",
            "[数据来源、收集方法和样本]",
            "",
            "## 分析方法",
            "[数据分析方法和技术]",
            "",
            "## 实验设置",
            "[实验环境和参数配置]",
            "",
            "## 评估指标",
            "[性能评估指标和标准]",
            "",
            "## 质量控制",
            "[确保研究质量的措施]"
        ]
        
        return "\n".join(method_parts)
    
    def _generate_results_structure(self, 
                                   section_template: SectionTemplate,
                                   config: StructureGenerationConfig,
                                   content_context: Dict[str, Any] = None) -> str:
        """生成结果结构"""
        results_parts = [
            "<!-- 结果结构 -->",
            "",
            "## 描述性统计",
            "[数据的基本统计描述]",
            "",
            "## 主要发现",
            "[核心实验结果和发现]",
            "",
            "## 统计分析",
            "[统计检验和显著性分析]",
            "",
            "## 图表展示",
            "[重要结果的可视化展示]",
            "",
            "## 结果验证",
            "[结果的可靠性和有效性验证]"
        ]
        
        return "\n".join(results_parts)
    
    def _generate_discussion_structure(self, 
                                     section_template: SectionTemplate,
                                     config: StructureGenerationConfig,
                                     content_context: Dict[str, Any] = None) -> str:
        """生成讨论结构"""
        discussion_parts = [
            "<!-- 讨论结构 -->",
            "",
            "## 结果解释",
            "[对主要发现的解释和分析]",
            "",
            "## 理论意义",
            "[结果的理论贡献和意义]",
            "",
            "## 实践价值",
            "[研究的实际应用价值]",
            "",
            "## 与前人研究的比较",
            "[与相关研究结果的比较]",
            "",
            "## 研究局限性",
            "[研究的限制和不足]",
            "",
            "## 未来研究方向",
            "[基于本研究的未来研究建议]"
        ]
        
        return "\n".join(discussion_parts)
    
    def _generate_conclusion_structure(self, 
                                     section_template: SectionTemplate,
                                     config: StructureGenerationConfig,
                                     content_context: Dict[str, Any] = None) -> str:
        """生成结论结构"""
        conclusion_parts = [
            "<!-- 结论结构 -->",
            "",
            "## 研究总结",
            "[研究工作的总体概括]",
            "",
            "## 主要发现",
            "[核心发现和结论]",
            "",
            "## 研究贡献",
            "[本研究的主要贡献]",
            "",
            "## 实际应用",
            "[研究结果的应用前景]",
            "",
            "## 未来工作",
            "[后续研究的方向和计划]"
        ]
        
        return "\n".join(conclusion_parts)
    
    # 组织规则方法
    def _apply_organization_rules(self, 
                                structure: ReportStructure,
                                config: StructureGenerationConfig) -> ReportStructure:
        """应用组织规则"""
        organized_structure = structure
        
        # 应用各种组织规则
        for rule_name, rule_function in self.organization_rules.items():
            try:
                organized_structure = rule_function(organized_structure, 1.0)
            except Exception as e:
                self.logger.warning(f"应用组织规则 {rule_name} 失败: {str(e)}")
        
        return organized_structure
    
    def _ensure_logical_flow(self, structure: ReportStructure, weight: float) -> ReportStructure:
        """确保逻辑流程"""
        # 检查章节顺序的逻辑性
        section_order_map = {
            SectionType.TITLE: 1,
            SectionType.ABSTRACT: 2,
            SectionType.KEYWORDS: 3,
            SectionType.INTRODUCTION: 4,
            SectionType.LITERATURE_REVIEW: 5,
            SectionType.RELATED_WORK: 5,
            SectionType.METHODOLOGY: 6,
            SectionType.RESULTS: 7,
            SectionType.EVALUATION: 8,
            SectionType.DISCUSSION: 9,
            SectionType.LIMITATIONS: 10,
            SectionType.CONCLUSION: 11,
            SectionType.FUTURE_WORK: 12,
            SectionType.ACKNOWLEDGMENTS: 13,
            SectionType.REFERENCES: 14,
            SectionType.APPENDIX: 15
        }
        
        # 按逻辑顺序排序章节
        structure.sections.sort(key=lambda x: section_order_map.get(x.section_type, 999))
        
        return structure
    
    def _balance_content_distribution(self, structure: ReportStructure, weight: float) -> ReportStructure:
        """平衡内容分布"""
        if not structure.sections:
            return structure
        
        # 计算当前内容分布
        total_words = sum(section.word_count for section in structure.sections)
        if total_words == 0:
            return structure
        
        # 计算理想的内容分布
        core_sections = [s for s in structure.sections if s.section_type in [
            SectionType.INTRODUCTION, SectionType.METHODOLOGY, 
            SectionType.RESULTS, SectionType.DISCUSSION, SectionType.CONCLUSION
        ]]
        
        if core_sections:
            avg_length = total_words // len(core_sections)
            
            # 调整过长或过短的章节
            for section in core_sections:
                if section.word_count > avg_length * 1.5:
                    # 章节过长，添加建议
                    section.content += f"\n\n<!-- 建议: 此章节内容较长({section.word_count}字)，考虑分解为子章节 -->"
                elif section.word_count < avg_length * 0.5 and section.word_count > 0:
                    # 章节过短，添加建议
                    section.content += f"\n\n<!-- 建议: 此章节内容较短({section.word_count}字)，考虑扩充内容 -->"
        
        # 重新计算平衡性评分
        word_counts = [s.word_count for s in core_sections if s.word_count > 0]
        if len(word_counts) > 1:
            mean_length = sum(word_counts) / len(word_counts)
            variance = sum((x - mean_length) ** 2 for x in word_counts) / len(word_counts)
            cv = (variance ** 0.5) / mean_length if mean_length > 0 else 1
            structure.content_balance = max(0, 1 - cv)
        
        return structure
    
    def _resolve_section_dependencies(self, structure: ReportStructure, weight: float) -> ReportStructure:
        """解决章节依赖关系"""
        # 定义章节依赖关系
        dependencies = {
            SectionType.RESULTS: [SectionType.METHODOLOGY],
            SectionType.DISCUSSION: [SectionType.RESULTS],
            SectionType.CONCLUSION: [SectionType.RESULTS, SectionType.DISCUSSION],
            SectionType.EVALUATION: [SectionType.METHODOLOGY]
        }
        
        # 检查依赖关系
        section_types = [s.section_type for s in structure.sections]
        
        for section_type, deps in dependencies.items():
            if section_type in section_types:
                missing_deps = [dep for dep in deps if dep not in section_types]
                if missing_deps:
                    # 添加缺失依赖的警告
                    section = structure.get_section_by_type(section_type)
                    if section:
                        warning = f"\n\n<!-- 警告: 此章节依赖于 {[d.value for d in missing_deps]}，但这些章节缺失 -->"
                        section.content += warning
        
        return structure
    
    def _optimize_coherence(self, structure: ReportStructure, weight: float) -> ReportStructure:
        """优化连贯性"""
        # 添加章节间的过渡提示
        for i, section in enumerate(structure.sections[:-1]):
            next_section = structure.sections[i + 1]
            
            # 在章节末尾添加过渡提示
            transition_hint = f"\n\n<!-- 过渡提示: 此处应该自然过渡到 {next_section.title} -->"
            section.content += transition_hint
        
        # 计算连贯性评分（简化版）
        structure.structure_coherence = 0.8  # 基础连贯性评分
        
        return structure
    
    # 辅助方法
    def _evaluate_condition(self, condition: str, context: Dict[str, Any]) -> bool:
        """评估条件"""
        # 简单的条件评估逻辑
        if condition.startswith("has_"):
            key = condition[4:]  # 移除 "has_" 前缀
            return context.get(key, False)
        elif condition.startswith("not_"):
            key = condition[4:]  # 移除 "not_" 前缀
            return not context.get(key, True)
        else:
            return context.get(condition, False)
    
    def _analyze_available_content(self, content: Dict[str, Any]) -> Dict[str, Any]:
        """分析可用内容"""
        analysis = {}
        
        for section_type, section_content in content.items():
            if isinstance(section_content, str):
                word_count = len(section_content.split())
                analysis[section_type] = {
                    'word_count': word_count,
                    'has_content': word_count > 0,
                    'is_substantial': word_count > 100,
                    'needs_expansion': word_count < 200
                }
            elif isinstance(section_content, dict):
                analysis[section_type] = {
                    'has_structured_content': True,
                    'content_keys': list(section_content.keys())
                }
        
        return analysis
    
    def _enhance_section_with_content(self, 
                                    section: ContentBlock,
                                    content: Any,
                                    config: StructureGenerationConfig) -> ContentBlock:
        """使用内容增强章节"""
        if isinstance(content, str) and content.strip():
            # 如果已有内容，进行合并
            if section.content.strip():
                section.content = f"{section.content}\n\n{content}"
            else:
                section.content = content
        elif isinstance(content, dict):
            # 结构化内容处理
            content_parts = []
            for key, value in content.items():
                content_parts.append(f"## {key}")
                content_parts.append(str(value))
                content_parts.append("")
            
            if content_parts:
                new_content = "\n".join(content_parts)
                if section.content.strip():
                    section.content = f"{section.content}\n\n{new_content}"
                else:
                    section.content = new_content
        
        # 更新统计信息
        section.update_statistics()
        
        return section
    
    def _adjust_section_based_on_analysis(self, 
                                        section: ContentBlock,
                                        analysis: Dict[str, Any],
                                        config: StructureGenerationConfig) -> ContentBlock:
        """根据分析调整章节"""
        if analysis.get('needs_expansion', False):
            section.content += "\n\n<!-- 建议: 此章节内容需要扩充 -->"
        
        if analysis.get('is_substantial', False):
            section.completeness_score = 0.8
        else:
            section.completeness_score = 0.4
        
        return section
    
    def _evaluate_structure_quality(self, structure: ReportStructure):
        """评估结构质量"""
        # 计算完整性
        completed_sections = sum(1 for s in structure.sections if s.content.strip() and not s.content.startswith('['))
        structure.completion_percentage = (completed_sections / len(structure.sections)) * 100 if structure.sections else 0
        
        # 计算整体质量
        quality_factors = [
            structure.structure_coherence,
            structure.content_balance,
            structure.completion_percentage / 100
        ]
        
        structure.overall_quality = sum(quality_factors) / len(quality_factors)
    
    def get_template_by_id(self, template_id: str) -> Optional[ReportTemplate]:
        """根据ID获取模板"""
        return self.templates.get(template_id)
    
    def list_available_templates(self) -> List[Dict[str, str]]:
        """列出可用模板"""
        return [
            {
                'id': template.template_id,
                'name': template.name,
                'type': template.report_type.value,
                'description': template.description
            }
            for template in self.templates.values()
        ]
    
    def export_structure_to_dict(self, structure: ReportStructure) -> Dict[str, Any]:
        """导出结构为字典"""
        return {
            'structure_id': structure.structure_id,
            'template_id': structure.template_id,
            'report_type': structure.report_type.value,
            'sections': [
                {
                    'section_type': section.section_type.value,
                    'title': section.title,
                    'content': section.content,
                    'word_count': section.word_count,
                    'completeness_score': section.completeness_score
                }
                for section in structure.sections
            ],
            'statistics': {
                'total_word_count': structure.total_word_count,
                'total_sections': structure.total_sections,
                'completion_percentage': structure.completion_percentage,
                'structure_coherence': structure.structure_coherence,
                'content_balance': structure.content_balance,
                'overall_quality': structure.overall_quality
            },
            'generated_time': structure.generated_time.isoformat(),
            'last_updated': structure.last_updated.isoformat()
        }